#include "loginwidget.h"
#include "ui_loginwidget.h"
#include <QDebug>
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include "mainwindow.h"

//全局变量
int LoginWidget::userId = 0;
QString LoginWidget::userName = "";
int LoginWidget::userRole = 0;

LoginWidget::LoginWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoginWidget)
{
    ui->setupUi(this);
    initWidget();
    connect(ui->edit_passwd, SIGNAL(returnPressed()), ui->btn_login, SIGNAL(clicked()), Qt::UniqueConnection); //绑定回车信号与登录按钮点击信号
}

LoginWidget::~LoginWidget()
{
    delete ui;
}

/**
 * @brief 初始化窗体
 */
void LoginWidget::initWidget()
{
    this->setWindowTitle("智慧小区系统-登录界面");
}

/**
 * @brief 登录按钮点击事件
 */
void LoginWidget::on_btn_login_clicked()
{
    QString username = this->ui->edit_username->text();
    QString passwd = this->ui->edit_passwd->text();

    //输入校验
    if (username.isEmpty()) {
        QMessageBox::information(this, "提示", "用户名不能为空", QMessageBox::Ok);
        return;
    }
    if (passwd.isEmpty()) {
        QMessageBox::information(this, "提示", "密码不能为空", QMessageBox::Ok);
        return;
    }

    //查询
    QSqlQuery query;
    query.prepare("SELECT id, role FROM user WHERE username = :username AND passwd = :passwd");
    query.bindValue(":username", username);
    query.bindValue(":passwd", passwd);
    if(!query.exec())
    {
        qDebug()<<query.lastError();
    }
    else
    {
        if (query.next())
        {
            int user_id = query.value(0).toInt();
            int role = query.value(1).toInt();
            qDebug() << QString("用户登录成功：userId:%1    username:%2    passwd:%3").arg(user_id).arg(username).arg(passwd);
            QMessageBox::information(this, "提示", "登录成功", QMessageBox::Ok);

            //全局变量
            LoginWidget::userId = user_id;
            LoginWidget::userName = username;
            LoginWidget::userRole = role;

            MainWindow *w = new MainWindow();
            w->setLoginWidgetRefer(this);
            w->show();
            this->hide();
        }
        else
        {
            qDebug() << "用户登录失败";
            QMessageBox::critical(this, "错误", "登录失败", QMessageBox::Ok);
        }

    }

}
